#!/bin/bash -eu
#
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

readonly user='<%= node['nagios']['config']['adminuser'] %>'

set +o errexit
passadmin="$(get_attribute_value "nagios-admin-password")"
configname="$(get_attribute_value "nagios-config-name")"
set -o errexit

if [[ ! -n "${passadmin}" ]]; then
  passfile=/var/tmp/nagios-admin-password
  echo 'Generating random admin password.'
  echo "Password is stored in ${passfile} file."
  echo 'Please, change it as soon as possible.'
  touch ${passfile}
  chown root:root ${passfile}
  chmod 600 $passfile
  export HOME=/root
  passadmin="$(openssl rand -base64 12)"
  echo "${passadmin}" > ${passfile}
  if [[ -n "${configname}" ]]; then
    echo 'Setting runtime variable.'
    gcloud beta runtime-config configs variables set nagiosPassword "${passadmin}" --is-text --config-name "${configname}"
  fi
fi

htpasswd -b -c /usr/local/nagios/etc/htpasswd.users "${user}" "${passadmin}"

